﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace WorldBankBBS.Data
{
    public partial class Subboard
    {
        public int GetUnreadMessagesForUser(Guid userUID)
        {
            bool needSave = false;
            using (var mh = new ModelHelper())
            {
                mh.BeginNewContext();

                var result = (from m in mh.Context.MessageUsers.Where(x => x.UserUID == userUID)
                    where !m.IsRead && m.Message.Thread.SubboardUID == SubboardUID
                    select m).ToList().Count();

                foreach (var thread in Threads)
                {
                    foreach (
                        var message in
                            thread.Messages.Where(m => m.MessageUsers.FirstOrDefault(x => x.UserUID == userUID) == null)
                        )
                    {
                        ++result;

                        var mu = new MessageUser
                        {
                            IsHidden = false,
                            IsRead = false,
                            MessageUID = message.MessageUID,
                            UserUID = userUID,
                        };

                        mh.Context.MessageUsers.Add(mu);

                        needSave = true;
                    }
                }

                if (needSave) mh.Context.SaveChanges();
                return result;
            }

            return 0;
        }
    }
}
